//微信小程序
const express = require('express');
const router = express.Router();
const { wxAppid, wxAppsecret } = require('../config');
const axios = require('axios');
const localStorage = require('localStorage')
var WXBizDataCrypt = require('../util/WXBizDataCrypt')


//根据微信临时code获取session等信息
router.post('/getSession', (req, res) => {
    let params = req.body;
    let js_code = params.code;
    axios.get('https://api.weixin.qq.com/sns/jscode2session?appid=' + wxAppid + '&secret=' + wxAppsecret + '&js_code=' + js_code + '&grant_type=authorization_code')
        .then(resposne => {
            if (typeof resposne.data.session_key != 'undefined') {
                localStorage.setItem('mvpWxKey', resposne.data.session_key)
            }
            res.send(resposne.data);
        }).catch(e => {
            res.send(e)
        })
})

//解密微信用户信息
router.post('/decodeData', (req, res) => {
    let encryptedData = req.body.encryptedData;
    let iv = req.body.iv;
    let sessionKey = localStorage.getItem('mvpWxKey');
    let pc = new WXBizDataCrypt(wxAppid, sessionKey);
    let data = pc.decryptData(encryptedData, iv);
    res.send(data)
})


module.exports = router;